package com.cssy.authority.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.byd.acegiext.domain.Role;
import com.byd.acegiext.service.PermissionService;
import com.byd.acegiext.service.RoleService;
import com.byd.acegiext.service.UserService;
import com.byd.acegiext.service.impl.PermissionServiceImpl;
import com.byd.acegiext.service.impl.RoleServiceImpl;
import com.byd.acegiext.service.impl.UserServiceImpl;
import com.cssy.authority.dao.AppSqlConfig;
import com.cssy.authority.entity.User;
import com.cssy.authority.service.IAuthorityService;
import com.cssy.authority.service.impl.AuthorityServiceImpl;
import com.cssy.authority.util.Company;
import com.cssy.authority.util.Page;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.plat.helper.JqGridHandler;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.JsonUtil;
import com.plat.util.json.OutJsonGrid;


/**
 * 用户角色管理
 * @author silver
 *
 */
@Controller
@RequestMapping("/security/role")
public class RoleController {
	private static final String MANAGER = "/security/role/Manager";
	private static final String EIDT = "/security/role/Operation";//添加、修改、显示页面
	private static final String ROLEPERMISSION = "/security/role/RolePermission";//添加、修改、显示页面
	private static Logger logger = LoggerFactory.getLogger(RoleController.class);
	private static final String companyId = "1";
	private RoleService rs = new RoleServiceImpl();
	private PermissionService ps = new PermissionServiceImpl();
	private UserService us = new UserServiceImpl();
	
	
	/**
	 * 保存角色权限关系
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/updateRolePermission")
	public void updateRolePermission(HttpServletRequest request,HttpServletResponse response)throws Exception {
		Map map = new HashMap();
		boolean resultFlag = true;
		try {
			String roleId =request.getParameter("roleId") ;//FormUtil.getString("roleId", mapRequest);
			String pmsData =request.getParameter("pmsData") ;// FormUtil.getString("pmsData", mapRequest);
			Role role = rs.getRoleById(roleId);
			if (roleId != null) {
				role.removeAllPermissions();
				JSONArray ja = JSONArray.fromObject(pmsData);
				for (int i = 0 ; i < ja.size() ; i++) {
					JSONObject jo = (JSONObject) ja.get(i);
					role.addPermission(jo.getString("id"));
				}
				rs.update(role);
			}
		}catch (Exception e) {
			resultFlag = false;
			e.printStackTrace();
		}
		map.put("resultFlag", resultFlag);
		JSONObject json= JSONObject.fromObject(map);
		AjaxUtil.printJSonStr(response, json.toString());
	}
	@RequestMapping("/managerRolePermission")
	public String managerRolePermission(HttpServletRequest request, Model model) throws Exception {
		String roleId=request.getParameter("roleId");
		Role role = rs.getRoleById(roleId);
		//获取权限相关信息
		List permissions = ps.getPermissionByRole(roleId, 0, -1);
	    List urlPermissions = ps.loadUrlPermission("1", 0, -1);
	    List methodPermissions = ps.loadMethodPermission("1", 0, -1);
	    List webresPermissions = ps.loadWebResPermission("1", 0, -1);
	    urlPermissions.addAll(methodPermissions);
	    urlPermissions.addAll(webresPermissions);
	    urlPermissions.removeAll(permissions);
	    Map map = new HashMap();
	    map.put("Total", permissions.size());
	    map.put("Rows", permissions);
	    
	    model.addAttribute("tempRole", role);
	    model.addAttribute("hasPms",JSONObject.fromObject(map) );
	    
	    map.put("Total", urlPermissions.size());
	    map.put("Rows", urlPermissions);
	    model.addAttribute("noPms", JSONObject.fromObject(map));
	    UserService us = new UserServiceImpl();
	    
	    List<User> users = us.getUsersByRole(roleId, 0, Integer.MAX_VALUE);
	    map.put("Total", users.size());
	    map.put("Rows", users);
	    model.addAttribute("users", JsonUtil.filterJson(map, true, true, new String[]{"password","userGroups","roleHolder"}));
		return ROLEPERMISSION;
	}
	/**
	 * 转到管理页面
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/manager")
	public String manager(HttpServletRequest request, Model model) throws Exception {
	
		return MANAGER;
	}
	//查询信息
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/list")
	public void list(HttpServletRequest request,HttpServletResponse response)throws Exception {
		JqGridHandler hander=new JqGridHandler(request);
		Page page=new Page(request);
		String partName=hander.getQueryValue("partName");
		int count = rs.countRolesByPartName(partName, companyId);
		List<Role> roles = rs.getRolesByPartName(partName, companyId, page.getStart(), page.getEnd());
		
		Map map = new HashMap();
		map.put("Total", count);
		map.put("Rows", com.cssy.authority.service.impl.RoleServiceImpl.domainToPojo(roles));
		OutJsonGrid out=new OutJsonGrid(map);
		out.printJSon(response);
	}	
	
	/**
	 * 表单操作（增加、编辑、显示）
	 */
	@RequestMapping(value = "/operate/{flag}/{id}")
	public String operationForm(HttpServletRequest request,@PathVariable String id,@PathVariable String flag, Model model) throws Exception{

		if(OperationFlag.ADD.equals(flag)){//我新增加时操作
			
		}else{
			Role role= rs.getRoleById(id);
			
			model.addAttribute("role", role);
			
		
		}
		return EIDT;
	}
	
	/**
	 * 保存并重定向到列表显示页面
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> save(HttpServletRequest request,@ModelAttribute @Valid  Role curAP,BindingResult result, Model model) {
		Map<String, Object> modelMap = new HashMap<String, Object>(3);
		try {
		//	Company
			curAP.setCompanyId(Company.getId());//获取权限 系统ID
			
			if(curAP.getId()==null){//验证新增状态		
				rs.save(curAP);
				modelMap.put("id", curAP.getId());
			    modelMap.put("success", "true");
			    modelMap.put("infor", GlobalResLoader.getOpsuccess());		
				
			}else{
			//companyId
			
				rs.update(curAP);
				modelMap.put("id", curAP.getId());
			    modelMap.put("success", "true");
			    modelMap.put("infor", GlobalResLoader.getOpsuccess());
			}
		} catch (Exception e) {			
			e.printStackTrace();
			logger.error("角色管理管理", e);
			modelMap.put("id", "");
	        modelMap.put("success", "false");
	        modelMap.put("infor", GlobalResLoader.getOpfailed()+e.getMessage());
		}
		
		return modelMap;
	}
	/**
	 * 删除并重定向到列表显示页面
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Map<String, Object> delete(HttpServletRequest request, HttpServletResponse response ,Model model){
		Map<String, Object> modelMap = new HashMap<String, Object>(2);
		try{
			SqlMapClient sqlMapClient = AppSqlConfig.getSqlMapInstance();
			IAuthorityService ias = new AuthorityServiceImpl(sqlMapClient);
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			//写法不合理须待改善
			for(String field : fields){
				Role role = rs.getRoleById(field);
				rs.remove(role);
			}
		
			 modelMap.put("success", "true");
		     modelMap.put("infor", GlobalResLoader.getOpsuccess());
		}catch(Exception e){
			logger.error("删除角色成功",e);
			e.printStackTrace();
			 modelMap.put("success", "false");
		     modelMap.put("infor", GlobalResLoader.getOpfailed()+e.getMessage());
		}
		return modelMap;
	}
}
